import React, {Component} from 'react';
import {Table, Spin, Button, Modal, Tree, message, Popconfirm} from "antd";
import $http from '../../../untils/request'
import {deepClone, formatterTime} from "../../../untils/auth";

class System extends React.Component {
    constructor() {
        super();
        this.state = {
            props: '',
            tableData: [],
            loading: true,
            visible: false,
            menuList: [],
            treeCheckList: [],
            dialogTitle: '',
            userId: '',
            page: {
                page: 1,
                pageSize: 10,
                total: 0
            }
        }
    }

    componentDidMount() {
        this.getDataList()
    }

    render() {
        const columns = [
            {
                title: '用户名',
                dataIndex: 'name',
                key: '1',
            },
            {
                title: '密码',
                dataIndex: 'password',
                key: '2',
            },
            {
                title: 'ID',
                dataIndex: 'key',
                key: '3',
            },
            {
                title: '注册时间',
                dataIndex: 'time',
                key: '4',
            },
            {
                title: '操作',
                dataIndex: '',
                key: '5',
                render: (text, record, index) => {
                    return (
                        <div>
                            <Button style={{marginRight: '10px'}}
                                    type='primary'
                                    size='small'
                                    onClick={() => this.getPowerList(record)}>设置权限</Button>
                            <Popconfirm title="确定删除？" okText="确认" cancelText="取消"
                                        onConfirm={e => this.deleteUser(record)}>
                                <Button size='small' type="primary"   danger>删除</Button>
                            </Popconfirm>

                        </div>
                    )
                }
            },
        ]
        const data = (data) => {
            const arr = data.map(item => {
                item.name = item.account
                item.key = item.userId
                item.time = formatterTime((item.registerTime / 1000).toString().substr(0, 10))
                return item
            })
            return arr
        }
        const pagination = {
            position: ['bottomCenter'],
            current: this.state.page.page,
            pageSize: this.state.page.pageSize,
            total: this.state.page.total,
            showTotal: () => `共 ${this.state.page.total} 条 `,
            onChange: (val) => this.currentPageChange(val)
        }
        return (
            <div>
                <Table pagination={pagination} loading={this.state.loading} columns={columns}

                       dataSource={data(this.state.tableData)}/>
                <Modal
                    title={this.state.dialogTitle}
                    visible={this.state.visible}
                    maskClosable={false}
                    onCancel={() => this.setState({visible: false, treeCheckList: []})}
                    onOk={() => this.onSubmitForm()}
                >
                    <Tree
                        checkable={true}
                        checkStrictly
                        onCheck={(keys, checkedNodes) => this.chekckTree(keys, checkedNodes)}
                        treeData={this.formatTreeData(this.state.menuList)}
                        checkedKeys={this.state.treeCheckList}
                    >
                    </Tree>
                </Modal>
            </div>
        )
            ;
    }

    async getDataList() {
        const params = {
            page: this.state.page.page,
            pageSize: this.state.page.pageSize
        }
        console.log(params)
        const res = await $http.get('/getUserList', {params})
        if (res.status === 200) {
            const {page, pageSize, total} = res
            this.setState({
                tableData: res.data,
                loading: false,
                page: {
                    page: page,
                    pageSize: pageSize,
                    total: total
                }
            })
        }
    }

    async deleteUser(row) {
        console.log(row)
        const {userId} = row
        const params = {
            id: userId
        }
        const res = await $http.get('/delUserList', {params})
        if (res.status === 200) {
            message.success(res.msg)
            this.getDataList()
        } else {
            message.error(res.msg)
        }
    }

    async currentPageChange(val) {
        const data = Object.assign({}, this.state.page, {page: val})
        await this.setState({
            page: data
        })
        this.getDataList()
    }

    formatTreeData(data) {
        data.map(item => {
            item.title = item.menuName
            item.key = item.id
            if (item.children) {
                this.formatTreeData(item.children)
            }
        })
        return data
    }

    async getPowerList(row) {
        console.log(row)
        let params = {
            id: row.userId
        }
        const res = await $http.get('/getNavList', {params})
        if (res.status === 200) {
            const defaultId = []
            res.powerlist.forEach(item => {
                defaultId.push(item)
            })
            this.setState({
                menuList: res.data,
                visible: true,
                userId: row.userId,
                dialogTitle: row.account,
                treeCheckList: defaultId
            })
        }
    }

    async onSubmitForm() {
        const obj = {}
        this.state.treeCheckList.forEach((item, index) => {
            obj[index] = item
        })
        const data = {
            powerSelect: JSON.stringify(obj),
            id: this.state.userId
        }
        const res = await $http.post('/addPowerList', data)
        if (res.status === 200) {
            message.success(res.msg)
            this.setState({
                visible: false
            })
        }
    }

    chekckTree(key, checkedNodes) {
        const checkNode = checkedNodes.node
        const treesKey = this.formatterTree([checkNode], checkedNodes.checked)
        this.setState({
            treeCheckList: treesKey
        })
    }

    formatterTree(data, flag) {
        let _list = []
        const app = (data, flag) => {
            for (let i = 0; i < data.length; i++) {
                if (data[i].children) {
                    app(data[i].children, flag)
                }
                if (flag) {
                    const checkList = this.state.treeCheckList
                    checkList.push(data[i].id)
                    _list = checkList
                } else {
                    this.state.treeCheckList.forEach((item, index) => {
                        const checkList = this.state.treeCheckList
                        if (item === data[i].id) {
                            checkList.splice(index, 1)
                            _list = checkList
                        }
                    })
                }
            }
            return _list
        }
        return app(data, flag)
    }
}

export default System;
